<template>
    <div style="display: flex">
      <div>
        <div>
          <input
            v-model="keywords"
            type="text"
            placeholder="请输入关键词"
            @input="onInput"
            style="width: 400px; padding: 5px; margin-right: 5px;"
          />
          <ul v-if="options.length > 0" style="list-style-type: none; padding: 0; margin: 0; border: 1px solid #ccc; max-height: 150px; overflow-y: auto;">
            <li
              v-for="item in options"
              :key="item.id"
              @click="selectOption(item)"
              style="padding: 5px; cursor: pointer; display: flex; justify-content: space-between; align-items: center;"
            >
              <span>{{ item.name }}</span>
              <span style="color: #8492a6; font-size: 13px;">{{ item.district }}</span>
            </li>
          </ul>
        </div>
        <div id="container" class="container"></div>
      </div>
      <div class="info-box">
        纬度：{{ form.lat }}
        <br />
        经度：{{ form.lng }}
        <p>详细地址：{{ form.address }}</p>
      </div>
    </div>
  </template>
  
  <script>
  import AMapLoader from "@amap/amap-jsapi-loader";
  window._AMapSecurityConfig = {
    securityJsCode: "1a2d406c82aa8e7916af12d9c901477e",
  };
  /* global AMap */
  export default {
    name: "TestIndex",
    data() {
      return {
        map: null,
        marker: null,
        geoCoder: null,
        AutoComplete: null,
        keywords: "",
        form: {
          lng: "",
          lat: "",
          address: "",
          adcode: "",
        },
        loading: false,
        options: [], // 确保 options 是一个数组
      };
    },
    methods: {
      initMap() {
        AMapLoader.load({
          key: "f8c954755588cd09132500151dc4d01c",
          version: "2.0",
          plugins: ["AMap.Geocoder", "AMap.AutoComplete"],
        })
          .then((AMap) => {
            this.map = new AMap.Map("container", {
              viewMode: "2D",
              zoom: 5,
              center: [105.602725, 37.076636],
            });
            this.geoCoder = new AMap.Geocoder({
              city: "010",
              radius: 1000,
            });
            this.AutoComplete = new AMap.AutoComplete({ city: "全国" });
            this.map.on("click", (e) => {
              this.form.lng = e.lnglat.lng;
              this.form.lat = e.lnglat.lat;
              this.removeMarker();
              this.setMapMarker();
            });
          })
          .catch((err) => {
            console.log(err);
          });
      },
  
      currentSelect(val) {
        if (!val || !val.location) {
          console.error('Invalid selection: val or val.location is undefined');
          return;
        }
        this.form = {
          lng: val.location.lng,
          lat: val.location.lat,
          address: `${val.district} ${val.address}`,
          adcode: val.adcode,
        };
        this.removeMarker();
        this.setMapMarker();
      },
  
      setMapMarker() {
        if (!this.map || !this.form.lng || !this.form.lat) return;
  
        this.map.setFitView();
        this.marker = new AMap.Marker({
          map: this.map,
          position: [this.form.lng, this.form.lat],
        });
        this.toGeoCoder();
        this.map.setFitView();
        this.map.add(this.marker);
      },
  
      removeMarker() {
        if (this.marker) {
          this.map.remove(this.marker);
          this.marker = null; // 确保 marker 被正确清除
        }
      },
  
      toGeoCoder() {
        const lnglat = [this.form.lng, this.form.lat];
        this.geoCoder.getAddress(lnglat, (status, result) => {
          if (status === 'complete' && result.regeocode) {
            this.form.address = result.regeocode.formattedAddress;
          }
        });
      },
  
      onInput() {
        if (this.keywords !== "") {
          this.loading = true;
          setTimeout(() => {
            this.loading = false;
            this.AutoComplete.search(this.keywords, (status, result) => {
              if (status === 'complete' && result.tips) {
                this.options = result.tips;
              } else {
                this.options = []; // 清空选项
              }
            });
          }, 200);
        } else {
          this.options = [];
        }
      },
  
      selectOption(val) {
        if (!val || !val.location) {
          console.error('Invalid selection: val or val.location is undefined');
          return;
        }
        this.form = {
          lng: val.location.lng,
          lat: val.location.lat,
          address: `${val.district} ${val.address}`,
          adcode: val.adcode,
        };
        this.options = [];
        this.removeMarker();
        this.setMapMarker();
      },
    },
    mounted() {
      this.initMap();
    },
  };
  </script>
  
  <style>
  .container {
    width: 500px;
    height: 300px;
  }
  
  .info-box {
    margin-left: 20px;
  }
  
  ul {
    background-color: white;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  }
/*   
  li:hover {
    background-color: #f5f5f5;
  } */
  </style>
  